<template>
  <div class="compilationSummary">
    <div class="contentTopTitle">
      <div class="fl">
        <div class="title">预算编制跟踪2020版</div>
      </div>
    </div>
    <div>
      <el-form :inline="true" :model="form" label-width="70px" class="formList">
        <el-form-item label="预算年度">
          <el-date-picker v-model="form.year" type="year" placeholder="选择年" value-format="yyyy"></el-date-picker>
        </el-form-item>
        <el-form-item label="区域">
          <dx-cascader
            :area_id.sync="form.areaId"
            :area_name.sync="form.areaName"
            :area_lvl.sync="form.areaLvl"
            ref="cascader"
          />
        </el-form-item>
        <el-form-item style="width: 90px;" v-if="flag == 2">
          <el-checkbox v-model="form.checked" >明细数据</el-checkbox>
        </el-form-item>
        <el-form-item class="wid100">
          {{form.autoService ? '自服务':'全业务'}}
          <el-switch v-model="form.autoService"></el-switch>
          <el-button size="small" style="margin-left: 12px" type="primary" @click="search">查询</el-button>
          <el-button size="small" type="orange" @click="batchxport()">批量导出</el-button>
          <el-button size="small" type="orange" @click="exportModal()">导出</el-button> 
        </el-form-item>
      </el-form>
    </div>
    <div class="table-content clearfix">
      <div class="content">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="总收入表" name="first">
            <tab1 :rowData="tableData" :colDefList="colDefList" ref="tab1" ></tab1>
          </el-tab-pane>
          <el-tab-pane label="主量业务表" name="second">
            <tab2 :rowData="tableData" :colDefList="colDefList" :isAll="form.checked" ref="tab2"></tab2>
          </el-tab-pane>
          <!-- <el-tab-pane label="TOBTOC" name="third">
             <tab3 :rowData="tableData" :colDefList="colDefList" ref="tab3"></tab3> 
          </el-tab-pane> -->
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
import tab1 from "@/views/budget/compilationSummary/budgeting-tab1";
import tab2 from "@/views/budget/compilationSummary/budgeting-tab2";
// import tab3 from "@/views/budget/compilationSummary/compilationSummary-tab3";
import prefixAPI from "@/api/prefixAPI";
import { getCookie } from "@/common/js/cookie";
import { getSessionStorage } from "@/common/js/storage";
import { $budgetAPI } from "@/api";
import FileSaver from 'file-saver';
import XLSX from 'xlsx';
export default {
  name: "historyBudgeting",
  components: {
    tab1,
    tab2,
    // tab3,
  },
  data() {
    return {
      backRecord: false,
      form: {
        year: "",
        areaId: "",
        autoService: false,
        checked: true
      },
      activeName: "first",
      flag: 1,
      accountInfo: "",
      tableData: [],
      colDefList: [],
      exportLoad: false,
    };
  },
  computed: {
    areaSelect() {
      return this.form.areaSelect;
    },
  },
  created() {
      var that = this;
    
      that.accountInfo = JSON.parse(getSessionStorage("accountInfo"));
      that.form.areaId = that.accountInfo.areaId;
      that.form.year = that.moment().subtract(1, "years").format("YYYY");
      // that.getYear();
  },
  // mounted() {
  //   this.init();
  // },
  methods: {
    //查询
    search() {
      let params = {
        year: this.form.year,
        areaId: this.form.areaId ? this.form.areaId : this.accountInfo.areaId,
        flag: this.flag,
        autoService: this.form.autoService,
      };
      this.listResourceData(params);
    },
    //导出
    exportModal() {
      // var that = this, titles = ['预算编制跟踪2021版-总收入表', '预算编制跟踪2021版-主量业务表'];

      // that.loading = this.$loading({
      //           lock: true,
      //           text: "正在导出",
      //           spinner: "el-icon-loading",
      //           background: "rgba(0, 0, 0, 0.7)"
      //       });

      // var xlsxParam = {
      //           raw: true
      //       }; //转换成excel时，使用原始的格式，这样导出的时候数字过长不会变成科学计数法
      //       let workbook = XLSX.utils.book_new();
      //       let ws1 = XLSX.utils.table_to_sheet(document.querySelector('#table' + that.flag), xlsxParam);
      //       XLSX.utils.book_append_sheet(workbook, ws1, titles[that.flag - 1]);
      //       let wbout = XLSX.write(workbook, {
      //           bookType: 'xlsx',
      //           bookSST: true,
      //           type: 'array'
      //       });
      //       try {
      //           FileSaver.saveAs(
      //               new Blob([wbout], {
      //                   type: 'application/octet-stream;charset=utf-8"'
      //               }),
      //               titles[that.flag - 1] + '.xlsx'
      //           );
      //           that.loading.close();
      //       } catch (e) {
      //           if (typeof console !== 'undefined') console.log(e, wbOut);
      //       }
      //       return wbout;  ?areaId=1&year=2020  

      var that = this, 
          areaId = that.form.areaId,
          year = that.form.year,
          token = getCookie("token"),
          service = that.form.autoService,
          urls = '/api/budgetMakingTrack/exportData?';

          window.location.href = prefixAPI.hp + urls + `areaId=${areaId}&autoService=${service}&year=${year}&token=${token}`;
    },

    // 批量导出
    batchxport() {
         var that = this, 
          areaId = that.form.areaId,
          year = that.form.year,
          token = getCookie("token"),
          service = that.form.autoService,
          urls = '/api/budgetMakingTrack/exportBatchData?';

          window.location.href = prefixAPI.hp + urls + `areaId=${areaId}&autoService=${service}&year=${year}&token=${token}`;
    },
    listResourceData(params) {
      var that = this;
      switch (params.flag) {
        case 1:
          that.$refs.tab1.tableLoading = true;
          $budgetAPI.getYSBZ2021(
            params, res => {
                that.tableData = [];
                that.colDefList = [];
                res.content.data.map(it => {
                  it.dataList.map((item, i) => {
                       it[item.acctMonth] = item.indexValue; 
                  })
                })
                that.tableData = res.content.data;
                that.colDefList = res.content.titles;
                that.$nextTick(()=> {
                    that.$refs.tab1.init();
                    that.$refs.tab1.tableLoading = false;
                });
            }
          )
          break;
        case 2:
          this.$refs.tab2.tableLoading = true;
          $budgetAPI.getYSBZ2021main(
            params, res => {
                var content = [];
                that.tableData = [];
                that.colDefList = [];

                for (var i = 0, j = 0, k = 0; i < 12; i++) {
                    var cur = res.content.data[0].dataList.slice(j, j + 6);
                    j += 6;
                    var data = [];
                    cur.map((it, index) => {
                        var num = 0;
                        if(i == 0) {
                          num = index;
                        } else {
                          num = (index) + 6 * i;
                        }
                        var obj = {
                          label: res.content.titles[index].horizonIndexName,
                          data: it.indexValue,
                          prop: it.acctMonth + num 
                        };
                        data.push(obj);
                    })
                    var info = {
                      label: (i + 1) + '月',
                      data: data
                    }
                    content.push(info);
                }
                var k = 0;
                res.content.data.map(it => {
                  if(!it.dataList.length) {
                    k += 1;
                  }
                  it.dataList.map((item, i) => {
                       it[item.acctMonth + i] = item.indexValue; 
                  })
                })
                if(k == res.content.data.length) {
                  console.log('no');
                  content.map(item => {
                    var obj = [ {
                        'label': "本月收入"
                      }, {
                        'label': "本月期末用户数"
                      }, {
                        'label': "本月净增用户数"
                      }, {
                        'label': "本月离网用户数"
                      }, {
                        'label': "本月新增用户数"
                      }, {
                        'label': "本月ARPU"
                    }];
                    item.data = obj;
                    
                    // item.data.map(it => {
                    //   var obj = [ {
                    //     'label': "本月收入"
                    //   }, {
                    //     'label': "本月期末用户数"
                    //   }, {
                    //     'label': "本月净增用户数"
                    //   }, {
                    //     'label': "本月离网用户数"
                    //   }, {
                    //     'label': "本月新增用户数"
                    //   }, {
                    //     'label': "本月ARPU"
                    //   }]
                    //   it.data = obj;
                    // })
                  })
                }
                that.tableData = res.content.data;
                that.colDefList = content;
                that.$nextTick(()=> {
                    that.$refs.tab2.init();
                    that.$refs.tab2.tableLoading = false;
                });
            }
          )
          break;
        case 3:
          // this.$refs.tab3.tableLoading = true;
          break;
      }
      // $budgetAPI.compilationSummary(
      //   params,
      //   (res) => {
      //     if (res.code == 0) {
      //       this.tableData = [];
      //       this.colDefList = [];
      //       this.tableData = res.content.data;
      //       this.colDefList = res.content.colDefList;

      //       this.$nextTick(() => {
      //         switch (params.flag) {
      //           case 1:
      //             this.$refs.tab1.init();
      //             this.$refs.tab1.tableLoading = false;
      //             break;
      //           case 2:
      //             this.$refs.tab2.init();
      //             this.$refs.tab2.tableLoading = false;
      //             break;
      //           case 3:
      //             this.$refs.tab3.init();
      //             this.$refs.tab3.tableLoading = false;
      //             break;
      //         }
      //       });
      //     } else {
      //       this.alertError(res);
      //     }
      //   },
      //   (err) => {}
      // );
    },
    init() {
        let that = this, params = {
          year: that.form.year,
          areaId: that.form.areaId ? that.form.areaId : that.accountInfo.areaId,
          flag: 1,
          autoService: that.form.autoService,
        };
        that.listResourceData(params);
        that.activeName = "first";
    },
    //数据点击切换页请求不同的数据
    handleClick(tab, event) {
      let params = {
        year: this.form.year,
        areaId: this.form.areaId ? this.form.areaId : this.accountInfo.areaId,
        flag: null,
        autoService: this.form.autoService,
      };
      if (tab.name == "first") {
        params.flag = 1;
        this.flag = 1;
        this.listResourceData(params);
      }
      if (tab.name == "second") {
        params.flag = 2;
        this.flag = 2;
        this.listResourceData(params);
      }
      if (tab.name == "third") {
        params.flag = 3;
        this.flag = 3;
        this.listResourceData(params);
      }
    },
    // 获取年份
    getYear() {
      $budgetAPI.getBudgetYear(
        {},
        (res) => {
          if (res.code == 0) {
            this.form.year = res.content;
            this.init();
          } else {
            this.alertError(res);
          }
        },
        (err) => {}
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.compilationSummary {
  .table-content {
    .table-header {
      display: flex;
      justify-content: space-between;

      .btn-right {
        display: flex;
      }

      .table-title {
        font-size: 14px;
        font-weight: bold;
        height: 30px;
        line-height: 30px;

        span {
          display: inline-block;
          width: 5px;
          height: 5px;
          background-color: #418ee9;
          border-radius: 1000%;
          overflow: hidden;
          margin-right: 10px;
          margin-bottom: 3px;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.compilationSummary {
  .formList {
    .el-form-item {
      width: 22%;
    }
    .el-form-item:last-child {
      width: 32%;
      .el-form-item__content {
        width: 100%;
      }
    }
    .el-form-item.btnBox {
      margin-bottom: 0px;
      width: 18%;
      margin-right: 0;

      .el-form-item__content {
        display: flex;
      }
    }
  }
}
</style>
